using System;
using System.Linq;
using NHibernate.Event;
using Caramel.Entities;

namespace Caramel.NHibernate.Entities
{
	public class PreUpdateEntityEventListener : IPreUpdateEventListener
	{
		#region IPreUpdateEventListener Members

		public virtual bool OnPreUpdate(PreUpdateEvent @event)
		{
			var mutable = @event.Entity as IMutable;

			if (mutable == null)
			{
				return false;
			}

			var updated = SystemTime.Now;
			var updatedBy = CurrentUser.Name;

			if (@event.Persister.PropertyNames.Contains("Updated"))
			{
				@event.State[Array.IndexOf(@event.Persister.PropertyNames, "Updated")] = updated;
			}

			if (@event.Persister.PropertyNames.Contains("UpdatedBy"))
			{
				@event.State[Array.IndexOf(@event.Persister.PropertyNames, "UpdatedBy")] = updatedBy;
			}

			mutable.Updated = updated;
			mutable.UpdatedBy = updatedBy;

			return false;
		}

		#endregion
	}
}
